# Author: Chris Moyer
from marajo.exceptions import Unauthorized
from marajo.appengine.filters import Filter
from marajo.appengine.api.users import User

class AuthFilter(Filter):
    """
    Basic Authentication Filter
    This handles logging the user in if they sent
    the auth header or just verifying they're 
    allowed to access this page.
    """

    def call(self):
        auth_header =  self.handler.request.environ.get("HTTP_AUTHORIZATION")
        if self.handler.user is None:
            if auth_header:
                auth_type, encoded_info = auth_header.split(None, 1)
                if auth_type.lower() == "basic":
                    unencoded_info = encoded_info.decode('base64')
                    username, password = unencoded_info.split(':', 1)
                    try:
                        user = User.find(username=username).next()
                    except:
                        raise Unauthorized()
                    if user.password == password:
                        self.handler.session['user'] = user.id
                        self.handler._user = user
        if self.handler.user is None:
            raise Unauthorized()
        if self.handler.config.get("require_auth_group"):
            if not self.handler.user.has_auth_group(self.handler.config.get("require_auth_group").strip()):
                raise Unauthorized()
